/***
 * Copyright (c) 2021-2031 murenchao
 * fig is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.software.fig.springutils

import org.eclipse.xtend.lib.annotations.Accessors
import org.springframework.beans.BeansException
import org.springframework.beans.factory.support.BeanDefinitionBuilder
import org.springframework.beans.factory.support.DefaultListableBeanFactory
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.context.ConfigurableApplicationContext

@Accessors
class RegisterBeanToSpring implements ApplicationContextAware{
	
	val static instance = new RegisterBeanToSpring();
	private new(){}	
	def static RegisterBeanToSpring getInstance(){
		return instance;
	}
	protected ApplicationContext applicationContext
	
	override setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
	
	def static Object getBean(Class<?> zlass){
		return RegisterBeanToSpring.instance.applicationContext.getBean(zlass);
	}
	def static void setSpring(ApplicationContext applicationContext){
		RegisterBeanToSpring.instance.applicationContext = applicationContext;
	}
	
	def register(String key,Class<?> zlass){
		var bean = BeanDefinitionBuilder.genericBeanDefinition(zlass);
		var config = applicationContext as ConfigurableApplicationContext;
		var registry = config.getBeanFactory() as DefaultListableBeanFactory
		registry.setAllowBeanDefinitionOverriding(true);
		if(registry.containsBeanDefinition(key)){
			registry.removeBeanDefinition(key);
		}
		registry.registerBeanDefinition(key,bean.getRawBeanDefinition());
	}
	
}
